<template>
  <view class="page-body flex-col">
    <SearchHead
      ref="SearchHead"
      @loadData="loadData"
      @resetSearch="resetSearch"
      :isModify.sync="isModify"
      :searchForm.sync="searchForm"
      :tabsList="tabsList"
    ></SearchHead>
    <scroll-view @scrolltolower="loadData()" scroll-y class="goods-scroll">
      <div v-if="pageData.list.length" class="goods-box">
        <div
          class="goods-item flex-y-center"
          v-for="(item, i) in pageData.list"
          :key="i"
        >
          <div @click="checkItem(i)" v-if="isModify" class="select-box">
            <div
              v-if="!item.check"
              class="iconfont icon-xuanzekuangmoren"
            ></div>
            <div v-else class="iconfont icon-success-fill price-color"></div>
          </div>
          <div class="flex-w-1 bg-fff u-p-24 bdrd-20">
            <div class="goods flex">
              <div class="left">
                <image :src="item.cover_pic" mode="aspectFill" />
              </div>
              <div class="right flex-w-1">
                <div class="font-w-600 u-line-2 u-m-b-6">{{ item.name }}</div>
                <div class="u-m-b-12 color-999 u-line-1 u-font-24">
                  {{ item.desc }}
                </div>
                <div class="goods-price">
                  <text class="price-color">
                    <text>¥</text>
                    <text style="font-size: 36rpx">{{
                      priceFilter(item.price)[0]
                    }}</text>
                    <text>{{ priceFilter(item.price)[1] }}</text>
                  </text>
                  <text class="color-999 u-font-24 font-del u-m-l-10"
                    >¥{{ item.original_price }}</text
                  >
                </div>
              </div>
            </div>

            <div class="flex-x-end flex-y-center u-m-t-24">
              <div v-if="item.is_bind == 1" @click="delGoods(item)" class="btn">
                移除服务
              </div>
              <div v-else @click="addGoods(item)" class="btn">选择服务</div>
            </div>
          </div>
        </div>

        <u-loadmore :status="pageData.status"></u-loadmore>
      </div>
      <div v-else>
        <u-empty mode="data"></u-empty>
      </div>
      <!-- 占位 -->
      <div v-if="isModify" class="goods-bottom"></div>
    </scroll-view>
    <!-- 弹框 -->
    <div v-if="isModify" class="fixed flex-y-center">
      <div @click="switchAll(!checkAll)" class="left flex-y-center">
        <div v-if="!checkAll" class="iconfont icon-xuanzekuangmoren"></div>
        <div v-else class="iconfont icon-success-fill price-color"></div>
        <div class="u-font-32">全部</div>
      </div>
      <div class="right">
        <div @click="addGoods({}, 'all')" class="bt">批量加入</div>
        <div @click="delGoods({}, 'all')" class="bt">批量移除</div>
      </div>
    </div>
  </view>
</template>
<script>
import { goodsList, delGoods, addGoods } from "@/api/service-home";
import SearchHead from "./components/search-head.vue";

export default {
  components: {
    SearchHead,
  },
  data() {
    return {
      pageData: {
        page: 1,
        list: [],
        status: "loadmore",
      },
      searchForm: {
        name: "",
        cat_id: "",
        orderby: 0,
        begin: "",
        end: "",
      },

      tabsList: [
        {
          name: "已选服务",
        },
        {
          name: "待选服务",
        },
        {
          name: "全部服务",
        },
      ],
      isModify: false,
    };
  },
  onLoad() {
    this.loadData();
  },
  onShow() {},
  methods: {
    /*
    reset: 是否重置数据
    isTotal:是否只获取统计数量
    */
    async loadData(reset = false, isTotal = false) {
      if (reset) {
        this.pageData = this.$options.data().pageData;
      }

      if (this.pageData.status == "nomore" && !isTotal) return;

      const res = await goodsList(
        {
          page: this.pageData.page,
          type: (() => {
            switch (this.$refs.SearchHead?.current || 0) {
              case 0:
                return 1;
              case 1:
                return 2;
              default:
                return 0;
            }
          })(),
          ...this.searchForm,
        },
        true
      );

      this.tabsList = [
        {
          name: `已选服务(${res.countGoodsBind || 0})`,
        },
        {
          name: `待选服务(${res.countGoodsBindNo || 0})`,
        },
        {
          name: `全部服务(${res.count || 0})`,
        },
      ];
      if (isTotal) return;
      this.pageData.list.push(...res.data.list);
      this.pageData.page++;
      this.pageData.status =
        res.data.totalCount <= this.pageData.list.length
          ? "nomore"
          : "loadmore";
    },

    // type: 单个商品还是多选
    async delGoods(item, type) {
      uni.showModal({
        title: "提示",
        content: "您确定移除该产品吗？",
        success: async ({ confirm }) => {
          if (confirm) {
            let ids = item.goods_id ? [item.goods_id] : [];

            if (type == "all") {
              ids = this.pageData.list
                .filter((it) => it.check)
                .map((it) => {
                  return it.goods_id;
                });
            }
            await delGoods({ ids: ids }, true);

            this.pageData.list = this.pageData.list.map((it) => {
              if (ids.some((it1) => it1 === it.goods_id)) {
                it.is_bind = 0;
              }
              return it;
            });
            this.loadData(false, true);
            this.$utils.toast("移除成功");
          }
        },
      });
    },
    // type: 单个商品还是多选
    async addGoods(item, type) {
      let ids = item.goods_id ? [item.goods_id] : [];
      if (type == "all") {
        ids = this.pageData.list
          .filter((it) => it.check)
          .map((it) => it.goods_id);
      }
      await addGoods({ ids: ids }, true);
      this.pageData.list = this.pageData.list.map((it) => {
        if (ids.some((it1) => it1 === it.goods_id)) {
          it.is_bind = 1;
        }
        return it;
      });
      this.loadData(false, true);
      this.$utils.toast("添加成功");
    },
    checkItem(index) {
      let item = JSON.parse(JSON.stringify(this.pageData.list[index]));
      item.check = !item.check;
      this.$set(this.pageData.list, index, item);
    },

    switchAll(check) {
      this.pageData.list = this.pageData.list.map((item) => {
        item.check = check;
        return item;
      });
    },

    resetSearch() {
      this.searchForm = this.$options.data().searchForm;
      this.loadData(true);
    },
  },
  computed: {
    priceFilter() {
      return function (price) {
        if (!price) return [0, ".00"];
        if (typeof price === "number") price = String(price);
        let arr = price.split(".");
        if (arr.length < 2) return [...arr, ".00"];
        return [arr[0], `.${arr[1]}`];
      };
    },
    checkAll() {
      return this.pageData.list.every((item) => item.check);
    },
  },
  watch: {},
  onReachBottom() {},
  onPullDownRefresh() {},
};
</script>
<style lang="scss" scoped>
.font-del {
  text-decoration: line-through;
}
.bg-fff {
  background: #fff;
}
.bdrd-20 {
  border-radius: 20rpx;
}
.price-color {
  color: #f0250e;
}
.page-body {
  height: 100vh;

  .goods-scroll {
    flex: 1;
    height: 0;
    background: #f2f2f2;
    padding: 0 24rpx 24rpx;
    .goods-item {
      margin-bottom: 24rpx;
      .select-box {
        .iconfont {
          width: 50rpx;
          height: 50rpx;
          line-height: 50rpx;
          text-align: center;
          font-size: 50rpx;
          margin-right: 20rpx;
          color: #666;
        }
        .price-color {
          color: #f0250e;
        }
      }

      .goods {
        .left {
          margin-right: 18rpx;
          width: 268rpx;
          height: 168rpx;
          > image {
            width: 100%;
            height: 100%;
            border-radius: 10rpx;
          }
        }

        .right {
          .goods-price {
            .price-color {
              color: #f0250e;
              font-size: 24rpx;
              font-weight: 600;
            }
          }
        }
      }

      .btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 144rpx;
        height: 58rpx;
        background: #fdf1f0;
        border-radius: 120rpx 120rpx 120rpx 120rpx;
        font-size: 24rpx;
        color: #f0250e;
      }
    }
  }

  .goods-bottom {
    box-sizing: content-box;
    height: 100rpx;
    padding-bottom: env(safe-area-inset-bottom);
  }
  .fixed {
    box-sizing: content-box;
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
    height: 100rpx;
    padding: 0 24rpx;
    padding-bottom: env(safe-area-inset-bottom);
    background: #fff;

    display: flex;
    justify-content: space-between;
    .left {
      .iconfont {
        width: 50rpx;
        height: 50rpx;
        line-height: 50rpx;
        text-align: center;
        font-size: 50rpx;
        color: #666;
      }
      .price-color {
        color: #f0250e;
      }
    }
    .right {
      display: flex;
      align-items: center;
      .bt {
        margin-left: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 192rpx;
        height: 72rpx;
        background: #f0250e;
        border-radius: 120rpx 120rpx 120rpx 120rpx;
        color: #ffffff;
        font-weight: 600;
      }
    }
  }
}
</style>
